from flask import Blueprint, render_template, redirect, request, url_for

from . import db
from .models import User

user = Blueprint('user', __name__)


@user.route('/index/', methods=['GET'])
def index():
    return render_template('user/index.html')


@user.route('/add/', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        p_user = request.form.get('username', None)
        p_email = request.form.get('email', None)
        p_password = request.form.get('password', None)

        if not p_user or not p_email or not p_password:
            return 'input error'

        newobj = User(username=p_user, email=p_email, password=p_password)
        db.session.add(newobj)
        db.session.commit()
        users = User.query.all()
        return render_template('user/add.html', users=users)
    users = User.query.all()
    return render_template('user/add.html', users=users)


@user.route("/upload/", endpoint="upload", methods=["POST"])
def upload_row():
    # 文件对象保存在request.files上，并且通过前端的input标签的name属性来获取
    fp = request.files.get("f1")
    # 保存文件到服务器本地
    fp.save("a.jpg")
    return redirect(url_for("user.index"))


@user.route('/show/')
def show():
    return 'user_show'
